import keyWord from '../../../modules/decormodel/keyword'
import HistoryKeyword from '../../../modules/decormodel/historykeyword'
import { Op } from 'sequelize'
import { sequelize } from '../../../modules/BaseDao'

class SearchDao {
  static searchDao = new SearchDao()
  getHistoryKeyWordsList() {
    return HistoryKeyword.findAll({
      raw: true,
    })
  }
  // 根据输入的关键字查询搜索关键字列表
  searchKeyWords(key: string) {
    return keyWord.findAll({
      raw: true,
      where: {
        keyword: { [Op.like]: `%${key}%` },
      },
    })
  }
  // 查询是否存在历史关键字
  searchHistoryKeyWords(historyKeyWord: string) {
    return HistoryKeyword.findOne({
      raw: true,
      where: {
        historykeyword: {
          [Op.like]: `${historyKeyWord}`,
        },
      },
    })
  }
  // 保存历史关键字方法
  saveHistoryKeyWords(historyKeyWord: string): Promise<[any, any]> {
    // 第一次保存所以是1
    const sql = `insert into historykeyword(historykeyword, clickcount) values('${historyKeyWord}',1)`
    return sequelize.query(sql)
  }
  // 更新历史关键字点击次数（每次加一）
  updateHistoryKeyWordCount(historykeyword: string): Promise<[any, any]> {
    const sql = `update historykeyword set clickcount=clickcount+1 where historykeyword='${historykeyword}'`
    return sequelize.query(sql)
  }
  async deleteHistoryKeyWord(id: number): Promise<number> {
    const deleteSql = `delete from historykeyword where id=${id}`
    await sequelize.query(deleteSql)
    const countSql = `SELECT COUNT(*) AS count FROM historykeyword`
    const [results]: any = await sequelize.query(countSql)
    const remainingCount: number = results[0].count
    return remainingCount
  }
  searchDecovery() {
    return HistoryKeyword.findAll({
      order: [['clickcount', 'desc']],
      raw: true,
      offset: 0,
      limit: 6,
    })
  }
}

export default SearchDao.searchDao
